from django.http import JsonResponse
from rest_framework import status

from traceback import format_exc
from traceback_with_variables import iter_exc_lines

import logging

logger = logging.getLogger("log")


class UnknowErr(Exception):
    code = -10000
    msg = "UnknowErr"


class RaffleBusyErr(Exception):
    code = -10001
    msg = "server is busy, please retry raffle"


class RightErr(Exception):
    code = -10002
    msg = "error right"


class NullErr(Exception):
    code = -10003
    msg = "obj is null"


class ReqMethodErr(Exception):
    code = -10004
    msg = "req mode is error"


class ValueErr(Exception):
    code = -10005
    msg = "value is error"


class ExtendBossGoodErr(Exception):
    code = -10006
    msg = "ExtendBoss only can have one non golbal good"


class NicknameIsTooLongErr(Exception):
    code = -10007
    msg = "nickname len must < 20"


class BalanceInsufficientErr(Exception):
    code = -10008
    msg = "pay type remain less than sum price"


class DeleteGoodErr(Exception):
    code = -10009
    msg = "good in user_pack or in game_good"


class OverlordErr(Exception):
    code = -10010
    msg = "Currently only one user can play the game"


def jq_try(func):
    def d(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            lines = []
            lines += list(iter_exc_lines(e))
            lines.append(format_exc())
            logger.fatal("\n".join(lines))
            return JsonResponse(
                {
                    "code": getattr(e, "code", -1),
                    "exception": str(e),
                    "msg": getattr(e, "msg", getattr(e, "message", "unknow error")),
                    "detail": getattr(e, "detail", "no detail"),
                },
                status=status.HTTP_400_BAD_REQUEST,
                json_dumps_params={"ensure_ascii": False},
            )

    return d
